package com.zhuozhou.jdyc.main.main.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.RequiresApi;

import com.zhuozhou.jdyc.R;
import com.zhuozhou.jdyc.api.UserAccountHelper;
import com.zhuozhou.jdyc.base.BaseFragment;
import com.zhuozhou.jdyc.databinding.FragmengCartBinding;
import com.zhuozhou.jdyc.main.goods.activity.GoodsDetailActivity;
import com.zhuozhou.jdyc.main.main.activity.MainActivity;
import com.zhuozhou.jdyc.main.main.activity.MerchantActivity;
import com.zhuozhou.jdyc.main.main.adapter.CartShopAdapter;
import com.zhuozhou.jdyc.main.main.adapter.CartTopAdapter;
import com.zhuozhou.jdyc.main.main.bean.BasicsShoppingBean;
import com.zhuozhou.jdyc.main.main.bean.TabItemBean;
import com.zhuozhou.jdyc.main.main.viewmodel.MainViewModel;
import com.zhuozhou.jdyc.main.settlement.activity.ShopSettlementActivity;
import com.zhuozhou.jdyc.util.apiUtil.NumberUtils;
import com.zhuozhou.jdyc.util.log.ToastUtils;
import com.zhuozhou.jdyc.wight.dialog.ConfirmDialog;
import com.zhuozhou.jdyc.wight.recyclerview.FullyGridLayoutManager;
import com.zhuozhou.jdyc.wight.recyclerview.MyLayoutManager;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Create by Once_ChuXy on 2021/8/20
 * Describe:
 */
public class CartFragment extends BaseFragment<MainViewModel, FragmengCartBinding> implements CartTopAdapter.OnTabItemClickListener {

    private CartTopAdapter cartTopAdapter;
    private CartShopAdapter cartShopAdapter;
    private BasicsShoppingBean basicsShoppingBean;
    private int topView = 1;
    private int position = -1;

    @Override
    protected int getLayoutId() {
        return R.layout.fragmeng_cart;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            ((MainActivity) getActivity()).setThemeBarAndToolBarColor(R.color.themeColor);
        }
        mViewModel.BasicsShoppingMutableLiveData.observe(this, v -> {
            basicsShoppingBean = v;
            List<TabItemBean> tabItemBeans = new ArrayList<>();
            tabItemBeans.add(new TabItemBean(1, v.getObj().getType().get(0).getNumber(), "普通商品", topView == 1));
            tabItemBeans.add(new TabItemBean(2, v.getObj().getType().get(1).getNumber(), "积分商品", topView == 2));
            tabItemBeans.add(new TabItemBean(3, v.getObj().getType().get(2).getNumber(), "易货商品", topView == 3));
            cartTopAdapter = new CartTopAdapter(getActivity());
            cartTopAdapter.setList(tabItemBeans);
            cartTopAdapter.setOnTabItemClickListener(this);
            binding.mRecyclerViewTop.setAdapter(cartTopAdapter);
            binding.mRecyclerViewTop.setLayoutManager(new FullyGridLayoutManager(getActivity(), 3) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            setCartShopAdapter(v);
        });
        mViewModel.shopSelectCouponsMutableLiveData.observe(this, v -> {
            BasicsShoppingBean bean;
            bean = basicsShoppingBean;
            if (bean.getObj().getObj().get(position).getPrice() >= Double.parseDouble(v.getObj().getPrice2()))
                bean.getObj().getObj().get(position).setPrice2(bean.getObj().getObj().get(position).getPrice() - Double.parseDouble(v.getObj().getPrice()));
            bean.getObj().getObj().get(position).setDiscountSelect(v.getObj());
            setCartShopAdapter(bean);
        });
        mViewModel.BasicsDelShoppingMutableLiveData.observe(this, v -> {
            mViewModel.getBasicsShopping(topView + "", UserAccountHelper.getUserID());
        });

        binding.llRadioAll.setOnClickListener(v -> {
            setAllRadio(!(Boolean) binding.radioAll.getTag());
            List<BasicsShoppingBean.ObjBeanX.ObjBean> list = new ArrayList<>();
            if (cartShopAdapter != null && cartShopAdapter.getList().size() != 0) {
                for (BasicsShoppingBean.ObjBeanX.ObjBean item : cartShopAdapter.getList()) {
                    item.setChecked((Boolean) binding.radioAll.getTag());
                    list.add(item);
                }
                cartShopAdapter.setList(list);
                cartShopAdapter.notifyDataSetChanged();
            }
        });

        binding.mScrollView.setOnScrollChangeListener((v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY >= (binding.mScrollView.getHeight() / 4)) {
                binding.imageTop.setVisibility(View.VISIBLE);
            }
            if (scrollY <= (binding.mScrollView.getHeight() / 4)) {
                binding.imageTop.setVisibility(View.GONE);
            }
        });

        binding.imageTop.setOnClickListener(v -> {
            binding.mScrollView.fullScroll(View.FOCUS_UP);
        });

        binding.tvSettlement.setOnClickListener(v -> {
            if (getCheckedShop(cartShopAdapter.getList()) == null) {
                ToastUtils.showShort("结算只允许单个店铺进行结算");
            } else if (getCheckedShop(cartShopAdapter.getList()).get(0).getShangpin().size() == 0) {
                ToastUtils.showShort("请选择需要结算的商品");
            } else {
                Intent intent = new Intent(getActivity(), ShopSettlementActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("shop", (Serializable) getCheckedShop(cartShopAdapter.getList()));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    public void setAllRadio(Boolean isChecked) {
        if (isChecked) {
            binding.radioAll.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.radio_true, 0, 0, 0);
            binding.radioAll.setTag(true);
        } else {
            binding.radioAll.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.radio_false_new, 0, 0, 0);
            binding.radioAll.setTag(false);
        }
    }

    public void setCartShopAdapter(BasicsShoppingBean v) {
        if (v.getObj().getObj().size() <= 0) {
            binding.tvNoGoods.setVisibility(View.VISIBLE);
            binding.mRecyclerViewShop.setVisibility(View.GONE);
            binding.llSettlement.setVisibility(View.GONE);
        } else {
            binding.tvNoGoods.setVisibility(View.GONE);
            binding.mRecyclerViewShop.setVisibility(View.VISIBLE);
            binding.llSettlement.setVisibility(View.VISIBLE);
            cartShopAdapter = new CartShopAdapter(getActivity());
            cartShopAdapter.setType(topView);
            cartShopAdapter.setList(v.getObj().getObj());
            cartShopAdapter.setOnCouponItemClickListener((position, couponId) -> {
                this.position = position;
                mViewModel.postShopSelectCoupons(cartShopAdapter.getList().get(position).getAdmin_id(), couponId, UserAccountHelper.getUserID());
            });
            cartShopAdapter.setOnItemSetMoneyListener((ps, p, type) -> {
                if (type == 0 || type == 2) {//重新计算合计金额{
                    String[] strings = getAllMoney(cartShopAdapter.getList());
                    binding.tvMoney.setText(strings[0]);
                    binding.tvSettlement.setText("结算" + (topView == 1 ? "" : topView == 2 ? ("(" + strings[1] + "积分)") :
                            ("(" + strings[1] + "易货积分)")));
                    setAllRadio(strings[2].equals("true"));
                }
                if (type == 1) {//删除单个商品
                    new ConfirmDialog(getActivity())
                            .setMessage("确定要删除该商品吗？")
                            .setOnSureClickListener(dialog -> {
                                mViewModel.postDelShopping(cartShopAdapter.getList().get(ps).getStore_id(), cartShopAdapter.getList().get(ps).getShangpin().get(p).getId(),
                                        cartShopAdapter.getList().get(ps).getShangpin().get(p).getSku(),
                                        topView + "", UserAccountHelper.getUserID());
                            })
                            .builder()
                            .show();
                } else if (type == 2) {//增删商品数量
                    mViewModel.postShoppingCount(cartShopAdapter.getList().get(ps).getStore_id(), cartShopAdapter.getList().get(ps).getShangpin().get(p).getId(),
                            cartShopAdapter.getList().get(ps).getShangpin().get(p).getNumber(),
                            cartShopAdapter.getList().get(ps).getShangpin().get(p).getSku(),
                            topView + "", UserAccountHelper.getUserID());
                } else if (type == 3) {//打开店铺详情页面
                    Intent in = new Intent(getActivity(), MerchantActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("id", cartShopAdapter.getList().get(ps).getAdmin_id() + "");
                    in.putExtras(bundle);
                    startActivity(in);
                } else if (type == 4) {//打开商品详情页面
                    if (topView == 1) {
                        Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("id", cartShopAdapter.getList().get(ps).getShangpin().get(p).getCommodity_id() + "");
                        bundle.putInt("type", topView);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else if (topView == 2) {
                        MainActivity mainActivity = (MainActivity) getActivity();
                        mainActivity.doSelect(mainActivity.getBinding().nvIntegral);
                    } else if (topView == 3) {
                        MainActivity mainActivity = (MainActivity) getActivity();
                        mainActivity.doSelect(mainActivity.getBinding().nvBarter);
                    }
                }
            });

            String[] strings = getAllMoney(v.getObj().getObj());
            binding.mRecyclerViewShop.setAdapter(cartShopAdapter);
            binding.mRecyclerViewShop.setLayoutManager(new MyLayoutManager(getActivity()));
            binding.tvMoney.setText(strings[0]);
            binding.tvSettlement.setText("结算" + (topView == 1 ? "" : topView == 2 ? ("(" + strings[1] + "积分)") :
                    ("(" + strings[1] + "易货积分)")));
            setAllRadio(strings[2].equals("true"));
        }
    }

    private String[] getAllMoney(List<BasicsShoppingBean.ObjBeanX.ObjBean> bean) {
        Double allMoney = 0.00;
        Double allIn = 0.00;
        String isAll = "true";
        int cont = 0;
        for (BasicsShoppingBean.ObjBeanX.ObjBean obj : bean) {
            for (BasicsShoppingBean.ObjBeanX.ObjBean.ShangpinBean shop : obj.getShangpin()) {
                if (shop.isChecked()) {
                    if (topView == 1 || topView == 2) {
                        allMoney = (allMoney + (shop.getNumber() * Double.parseDouble(shop.getGoods_price())));
                        if (cont == 0 && obj.getDiscountSelect() != null && obj.getDiscountSelect().getPrice2() != null && allMoney >= Double.parseDouble(obj.getDiscountSelect().getPrice2())) {
                            allMoney = allMoney - Double.parseDouble(obj.getDiscountSelect().getPrice());
                            cont = 1;
                        }
                    }
                    if (topView == 2)
                        allIn = (allIn + (shop.getNumber() * Double.parseDouble(shop.getIntegral())));
                    if (topView == 3)
                        allIn = (allIn + (shop.getNumber() * Double.parseDouble(shop.getYibi())));
                } else {
                    isAll = "false";
                }
            }
            cont = 0;
        }
        return new String[]{NumberUtils.decimalFormat(String.valueOf(allMoney)), allIn == 0 ? "0" : allIn + "", isAll};
    }

    private List<BasicsShoppingBean.ObjBeanX.ObjBean> getCheckedShop(List<BasicsShoppingBean.ObjBeanX.ObjBean> bean) {
        List<BasicsShoppingBean.ObjBeanX.ObjBean> list = new ArrayList<>();
        List<BasicsShoppingBean.ObjBeanX.ObjBean.ShangpinBean> shopList = new ArrayList<>();
        Set<BasicsShoppingBean.ObjBeanX.ObjBean> count = new HashSet();
        for (BasicsShoppingBean.ObjBeanX.ObjBean obj : bean) {
            if (obj.isChecked()) {
                count.add(obj);
            }
            if (obj.isChecked() && obj.getShangpin().size() != 0) {
                for (BasicsShoppingBean.ObjBeanX.ObjBean.ShangpinBean shop : obj.getShangpin()) {
                    if (shop.isChecked()) {
                        shopList.add(shop);
                    }
                }
            }
        }
        if (count.size() > 1) {
            return null;
        }
        list.add((BasicsShoppingBean.ObjBeanX.ObjBean) count.toArray()[0]);
        list.get(0).setShangpin(shopList);
        return list;
    }

    @Override
    protected void initData(Bundle bundle) {
        mViewModel.getBasicsShopping(topView + "", UserAccountHelper.getUserID());
    }

    @Override
    public void onTabItemClick(View view, int position) {
        topView = cartTopAdapter.getList().get(position).getId();
        mViewModel.getBasicsShopping(topView + "", UserAccountHelper.getUserID());
    }
}
